import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wu_you/data/cache/username_password_cache.dart';
import 'package:wu_you/data/repository/auth_repository.dart';
import 'package:wu_you/data/repository/user_repository.dart';
import 'package:wu_you/l10n/messages.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/utils/input_util.dart';
import 'package:wu_you/utils/navigator_util.dart';
import 'package:wu_you/utils/utils.dart';
import 'package:wu_you/widgets/countdown_view.dart';

///修改密码
class ChangePassWordPage extends StatefulWidget{
  final String phone;
  ChangePassWordPage({Key key,this.phone}):super(key: key);
  @override
  ChangePassWordPageState createState() => ChangePassWordPageState();
}
class ChangePassWordPageState extends State<ChangePassWordPage>{
  var message;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("${message['cp1']}"),
      ),
      body: Column(
        children: [
          ListTile(
            tileColor: Colors.white,
            title: Text('${message['cp2']}', style: TextStyle(color: AppColors.textColor, fontSize: 14),),
            trailing: Icon(Icons.keyboard_arrow_right),
            onTap: () {
              NavigatorUtil.navigateToPage(context, EditLoginPasswordPage(phone: widget.phone,));
            },
          ),
          Divider(thickness: 1,),
          ListTile(
            tileColor: Colors.white,
            title: Text('${message['cp3']}', style: TextStyle(color: AppColors.textColor, fontSize: 14),),
            trailing: Icon(Icons.keyboard_arrow_right),
            onTap: () {
              NavigatorUtil.navigateToPage(context, EditTradePasswordPage(phone: widget.phone,));
            },
          ),
          Divider(thickness: 1,),
        ],
      ),
    );
  }
}




///修改登录密码
class EditLoginPasswordPage extends StatefulWidget{
  final String phone;
  EditLoginPasswordPage({Key key,this.phone}):super(key: key);
  @override
  EditLoginPasswordPageState createState() => EditLoginPasswordPageState();
}
class EditLoginPasswordPageState extends State<EditLoginPasswordPage>{
  final _formKey = GlobalKey<FormState>();
  final _countdownKey = GlobalKey<CountdownViewState>();
  String _pwd1;
  String _pwd2;
  String _smsCode;
  bool showPwd1 = false;
  bool showPwd2 = false;
  @override
  void initState() {
    super.initState();
  }
  var message;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text("${message['cp2']}"),
      ),
      body: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.only(left: 25,right: 25,top: 20,bottom: 20),
            child: Form(
              key: _formKey,
              child: Column(
                children: [
                  TextFormField(
                    style: TextStyle(fontSize: 15,color: AppColors.textColor),
                    maxLines: 1,
                    textAlignVertical: TextAlignVertical.center,
                    textInputAction: TextInputAction.done,
                    keyboardType: TextInputType.number,
                    autofocus: false,
                    obscureText: showPwd1 ? false : true,
                    cursorColor: Theme.of(context).primaryColor,
                    validator: (value) {
                      return value.length == 0 ? '${message['cp4']}' : null;
                    },
                    onSaved: (value){
                      _pwd1 = value;
                    },

                    textAlign: TextAlign.start,
                    decoration: InputDecoration(
                      fillColor: Colors.white,
                      filled: true,
                      border: UnderlineInputBorder(
                        borderSide: BorderSide.none,
                        // borderRadius: const BorderRadius.all(Radius.circular(24)),
                      ),
                      suffixIcon: IconButton(
                        splashColor: Colors.transparent,
                        highlightColor: Colors.transparent,
                        constraints: BoxConstraints.loose(Size(24, 24)),
                        iconSize: 18,
                        icon: Image.asset(showPwd1 ? Utils.getImgPath('ic_password_yes') : Utils.getImgPath('ic_password_no'),width: 18,height: 18,),
                        onPressed: () {
                          showPwd1 = !showPwd1;
                          setState(() {});
                        },
                      ),
                      prefixIconConstraints: BoxConstraints.loose(Size(64, 50)),
                      errorMaxLines: 1,
                      counterText: '',
                      contentPadding: EdgeInsets.only(left: 10),
                      hintText: "${message['cp4']}",
                      hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
                    ),
                  ),
                  Divider(
                    height: 2,
                    color: HexColor("#EAEAEA"),
                  ),
                  TextFormField(
                    style: TextStyle(fontSize: 15,color: AppColors.textColor),
                    maxLines: 1,
                    textAlignVertical: TextAlignVertical.center,
                    textInputAction: TextInputAction.done,
                    keyboardType: TextInputType.number,
                    autofocus: false,
                    obscureText: showPwd2 ? false : true,
                    cursorColor: Theme.of(context).primaryColor,
                    validator: (value) {
                      return value.length == 0 ? '${message['cp4']}' : null;
                    },
                    onSaved: (value){
                      _pwd2 = value;
                    },
                    textAlign: TextAlign.start,
                    decoration: InputDecoration(
                      fillColor: Colors.white,
                      filled: true,
                      border: UnderlineInputBorder(
                        borderSide: BorderSide.none,
                        // borderRadius: const BorderRadius.all(Radius.circular(24)),
                      ),
                      suffixIcon: IconButton(
                        splashColor: Colors.transparent,
                        highlightColor: Colors.transparent,
                        constraints: BoxConstraints.loose(Size(24, 24)),
                        iconSize: 18,
                        icon: Image.asset(showPwd2 ? Utils.getImgPath('ic_password_yes') : Utils.getImgPath('ic_password_no'),width: 18,height: 18,),
                        onPressed: () {
                          showPwd2 = !showPwd2;
                          setState(() {});
                        },
                      ),
                      prefixIconConstraints: BoxConstraints.loose(Size(64, 50)),
                      errorMaxLines: 1,
                      counterText: '',
                      contentPadding: EdgeInsets.only(left: 10),
                      hintText: "${message['cp5']}",
                      hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
                    ),
                  ),
                  Divider(
                    height: 2,
                    color: HexColor("#EAEAEA"),
                  ),
                  TextFormField(
                    style: TextStyle(color: Colors.black,fontSize: 15),
                    maxLines: 1,
                    textAlignVertical: TextAlignVertical.center,
                    textInputAction: TextInputAction.done,
                    maxLength: 4,
                    keyboardType: TextInputType.numberWithOptions(),
                    autofocus: false,
                    obscureText: false,
                    cursorColor: Theme.of(context).primaryColor,
                    validator: (value) {
                      return value.length == 4 ? null : '${message['enterCode']}';
                    },
                    onSaved: (value) {
                      _smsCode = value;
                    },
                    decoration: InputDecoration(
                      fillColor: Colors.white,
                      filled: true,
                      prefixIconConstraints: BoxConstraints.loose(Size(64, 50)),
                      suffixIconConstraints: BoxConstraints.loose(Size(100, 56)),
                      suffixIcon: CountdownView(
                        key: _countdownKey,
                        hint: Text(
                          "${message['getCode']}",
                          style: TextStyle(color: AppColors.primaryColor, fontSize: 14),
                        ),
                        onPressed: () {
                          closeKeyboard(context);
                          _onGetCode();
                        },
                      ),
                      border: UnderlineInputBorder(
                        borderSide: BorderSide.none,
                        borderRadius: const BorderRadius.all(Radius.circular(24)),
                      ),
                      errorMaxLines: 1,
                      counterText: '',
                      contentPadding: EdgeInsets.only(left: 10, right: 16),
                      hintText: "${message['enterCode']}",
                      hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
                    ),
                  ),
                  Divider(
                    height: 2,
                    color: HexColor("#EAEAEA"),
                  ),

                  SizedBox(height: 20,),

                  SizedBox(
                    width: double.infinity,
                    height: 42,
                    child: ElevatedButton(
                      child: Text("${message['cp6']}"),
                      style: ButtonStyle(
                        backgroundColor: MaterialStateProperty.all(AppColors.primaryColor),
                        shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(8))),//圆角弧度
                      ),
                      onPressed: _onEditPwd,
                    ),
                  ),
                ],
              ),
            ),
          )
      ),
    );
  }

  void _onGetCode(){

    _countdownKey.currentState.state = CountdownState.loading;
    LoadingApi.func(AuthRepository().getSmsCode(4,phone: widget.phone), context,showLoading: false,complete: (value){
      _countdownKey.currentState.state = CountdownState.countdown;
      ToastUtils.show("$value", context);
    },error: (error){
      _countdownKey.currentState.state = CountdownState.init;
      ToastUtils.show("$error", context);
    });
  }
  void _onEditPwd(){
    var _state = _formKey.currentState;
    _state.save();
    if (!_state.validate()) {
      return;
    }
    if(_pwd1 != _pwd2){
      ToastUtils.show("${message['pwdInconformity']}", context);
      return;
    }

    LoadingApi.func(UserRepository().changeLoginPwd(_pwd2, _smsCode), context,complete: (v){
      ToastUtils.show("${message['Success']}", context);
      Navigator.pop(context);
    },error: (e){
      ToastUtils.show("$e", context);
    });
  }
}








///修改交易密码
class EditTradePasswordPage extends StatefulWidget{
  final String phone;
  EditTradePasswordPage({Key key,this.phone}):super(key: key);
  @override
  EditTradePasswordPageState createState() => EditTradePasswordPageState();
}
class EditTradePasswordPageState extends State<EditTradePasswordPage>{
  final _formKey = GlobalKey<FormState>();
  final _countdownKey = GlobalKey<CountdownViewState>();
  String _pwd1;
  String _pwd2;
  String _smsCode;
  bool showPwd1 = false;
  bool showPwd2 = false;

  @override
  void initState() {
    super.initState();
  }
  var message;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text("${message['cp3']}"),
      ),
      body: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.only(left: 25,right: 25,top: 20,bottom: 20),
            child: Form(
              key: _formKey,
              child: Column(
                children: [
                  TextFormField(
                    style: TextStyle(fontSize: 15,color: AppColors.textColor),
                    maxLines: 1,
                    textAlignVertical: TextAlignVertical.center,
                    textInputAction: TextInputAction.done,
                    maxLength: 6,
                    // keyboardType: TextInputType.number,
                    autofocus: false,
                    obscureText: showPwd1 ? false : true,
                    cursorColor: Theme.of(context).primaryColor,
                    validator: (value) {
                      return value.length == 6 ? null : '${message['cp7']}';
                    },
                    onSaved: (value){
                      _pwd1 = value;
                    },
                    keyboardType: TextInputType.numberWithOptions(decimal: true),
                    inputFormatters: [
                      // PrecisionLimitFormatter(0),
                      FilteringTextInputFormatter.allow(RegExp('[0-9,]+'))
                    ],
                    textAlign: TextAlign.start,
                    decoration: InputDecoration(
                      fillColor: Colors.white,
                      filled: true,
                      border: UnderlineInputBorder(
                        borderSide: BorderSide.none,
                        // borderRadius: const BorderRadius.all(Radius.circular(24)),
                      ),
                      suffixIcon: IconButton(
                        splashColor: Colors.transparent,
                        highlightColor: Colors.transparent,
                        constraints: BoxConstraints.loose(Size(24, 24)),
                        iconSize: 18,
                        icon: Image.asset(showPwd1 ? Utils.getImgPath('ic_password_yes') : Utils.getImgPath('ic_password_no'),width: 18,height: 18,),
                        onPressed: () {
                          showPwd1 = !showPwd1;
                          setState(() {});
                        },
                      ),
                      prefixIconConstraints: BoxConstraints.loose(Size(64, 50)),
                      errorMaxLines: 1,
                      counterText: '',
                      contentPadding: EdgeInsets.only(left: 10),
                      hintText: "${message['cp7']}",
                      hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
                    ),
                  ),
                  Divider(
                    height: 2,
                    color: HexColor("#EAEAEA"),
                  ),
                  TextFormField(
                    style: TextStyle(fontSize: 15,color: AppColors.textColor),
                    maxLines: 1,
                    textAlignVertical: TextAlignVertical.center,
                    textInputAction: TextInputAction.done,
                    maxLength: 6,
                    // keyboardType: TextInputType.number,
                    autofocus: false,
                    obscureText: showPwd2 ? false : true,
                    cursorColor: Theme.of(context).primaryColor,
                    validator: (value) {
                      return value.length == 6 ? null : '${message['cp4']}';
                    },
                    onSaved: (value){
                      _pwd2 = value;
                    },
                    keyboardType: TextInputType.numberWithOptions(decimal: true),
                    inputFormatters: [
                      // PrecisionLimitFormatter(0),
                      FilteringTextInputFormatter.allow(RegExp('[0-9,]+'))
                    ],
                    textAlign: TextAlign.start,
                    decoration: InputDecoration(
                      fillColor: Colors.white,
                      filled: true,
                      border: UnderlineInputBorder(
                        borderSide: BorderSide.none,
                        // borderRadius: const BorderRadius.all(Radius.circular(24)),
                      ),
                      suffixIcon: IconButton(
                        splashColor: Colors.transparent,
                        highlightColor: Colors.transparent,
                        constraints: BoxConstraints.loose(Size(24, 24)),
                        iconSize: 18,
                        icon: Image.asset(showPwd2 ? Utils.getImgPath('ic_password_yes') : Utils.getImgPath('ic_password_no'),width: 18,height: 18,),
                        onPressed: () {
                          showPwd2 = !showPwd2;
                          setState(() {});
                        },
                      ),
                      prefixIconConstraints: BoxConstraints.loose(Size(64, 50)),
                      errorMaxLines: 1,
                      counterText: '',
                      contentPadding: EdgeInsets.only(left: 10),
                      hintText: "${message['cp5']}",
                      hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
                    ),
                  ),
                  Divider(
                    height: 2,
                    color: HexColor("#EAEAEA"),
                  ),
                  TextFormField(
                    style: TextStyle(color: Colors.black,fontSize: 15),
                    maxLines: 1,
                    textAlignVertical: TextAlignVertical.center,
                    textInputAction: TextInputAction.done,
                    maxLength: 4,
                    keyboardType: TextInputType.numberWithOptions(),
                    autofocus: false,
                    obscureText: false,
                    cursorColor: Theme.of(context).primaryColor,
                    validator: (value) {
                      return value.length == 4 ? null : '${message['enterCode']}';
                    },
                    onSaved: (value) {
                      _smsCode = value;
                    },
                    decoration: InputDecoration(
                      fillColor: Colors.white,
                      filled: true,
                      prefixIconConstraints: BoxConstraints.loose(Size(64, 50)),
                      suffixIconConstraints: BoxConstraints.loose(Size(100, 56)),
                      suffixIcon: CountdownView(
                        key: _countdownKey,
                        hint: Text(
                          "${message['getCode']}",
                          style: TextStyle(color: AppColors.primaryColor, fontSize: 14),
                        ),
                        onPressed: () {
                          closeKeyboard(context);
                          _onGetCode();
                        },
                      ),
                      border: UnderlineInputBorder(
                        borderSide: BorderSide.none,
                        borderRadius: const BorderRadius.all(Radius.circular(24)),
                      ),
                      errorMaxLines: 1,
                      counterText: '',
                      contentPadding: EdgeInsets.only(left: 10, right: 16),
                      hintText: "${message['enterCode']}",
                      hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
                    ),
                  ),
                  Divider(
                    height: 2,
                    color: HexColor("#EAEAEA"),
                  ),

                  SizedBox(height: 20,),

                  SizedBox(
                    width: double.infinity,
                    height: 42,
                    child: ElevatedButton(
                      child: Text("${message['cp6']}"),
                      style: ButtonStyle(
                        backgroundColor: MaterialStateProperty.all(AppColors.primaryColor),
                        shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(8))),//圆角弧度
                      ),
                      onPressed: _onEditPwd,
                    ),
                  ),
                ],
              ),
            ),
          )
      ),
    );
  }

  void _onGetCode(){
    _countdownKey.currentState.state = CountdownState.loading;
    LoadingApi.func(AuthRepository().getSmsCode(7,phone: widget.phone), context,showLoading: false,complete: (value){
      _countdownKey.currentState.state = CountdownState.countdown;
      ToastUtils.show("$value", context);
    },error: (error){
      _countdownKey.currentState.state = CountdownState.init;
      ToastUtils.show("$error", context);
    });
  }
  void _onEditPwd(){
    var _state = _formKey.currentState;
    _state.save();
    if (!_state.validate()) {
      return;
    }
    if(_pwd1 != _pwd2){
      ToastUtils.show("${message['pwdInconformity']}", context);
      return;
    }

    bool num = isNumber(_pwd2);
    if(!num){
      ToastUtils.show("${message['cp7']}", context);
      return;
    }
    LoadingApi.func(UserRepository().setTradePassword(_pwd2, _smsCode), context,complete: (v){
      ToastUtils.show("${message['Success']}", context);
      Navigator.pop(context);
    },error: (e){
      ToastUtils.show("$e", context);
    });
  }


  // 验证是否为数字
  bool isNumber(String str) {
    final reg = RegExp(r"^[0-9_]+$");
    print('$str 是否数字:${reg.hasMatch(str)}');
    return reg.hasMatch(str);
  }
}